package itsen.com.bduidemo.modle.system.service;

import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.support.annotation.Nullable;

import itsen.com.bduidemo.lib.thread.ThreadPool;
import itsen.com.bduidemo.lib.tool.LogTool;

/**
 * Created by zhoud on 2018/2/4.
 */

public class ServiceBtype extends Service {
    private final String TAG = "TestService2";
    private CallBack callBack;
    private int count = 0;
    private boolean quit;

    //定义onBinder方法所返回的对象

    private MyBinder binder = new MyBinder();
    public class MyBinder extends Binder
    {
        public ServiceBtype getService(){
            return ServiceBtype.this;
        }
        public int getCount()
        {
            return count;
        }
    }

    //必须实现的方法,绑定改Service时回调该方法  
    @Override
    public IBinder onBind(Intent intent) {
        LogTool.e(TAG, "onBind方法被调用!");
        return binder;
    }

    //Service被创建时回调  
    @Override
    public void onCreate() {
        super.onCreate();
        LogTool.e(TAG, "onCreate方法被调用!");
        //创建一个线程动态地修改count的值  

        ThreadPool.getmFixedThreadPool().submit(new Runnable() {
            @Override
            public void run() {
                while(!quit)
                {
                    try
                    {
                        Thread.sleep(1000);
                        if (callBack!=null){
                            callBack.call(""+count);
                        }
                    }catch(InterruptedException e){e.printStackTrace();}
                    count++;
                }
            }
        });

    }

    //Service断开连接时回调  
    @Override
    public boolean onUnbind(Intent intent) {
        LogTool.e(TAG, "onUnbind方法被调用!");
        return true;
    }

    //Service被关闭前回调  
    @Override
    public void onDestroy() {
        super.onDestroy();
        this.quit = true;
        LogTool.e(TAG, "onDestroyed方法被调用!");
    }

    @Override
    public void onRebind(Intent intent) {
        LogTool.e(TAG, "onRebind方法被调用!");
        super.onRebind(intent);
    }

    public interface CallBack{
        void call(String msg);
    }

    public CallBack getCallBack() {
        return callBack;
    }

    public void setCallBack(CallBack callBack) {
        this.callBack = callBack;
    }
}
